import type { LoginReq } from '@/api/type'
import type { DataInfo } from '@/utils/auth'
import { userApi } from '@/api'
import { resetRouter, router } from '@/router'
import { removeToken, setToken } from '@/utils/auth'
import { useMultiTagsStore } from '../modules/multiTags'
import { routerArrays } from '../utils'

export const useUserStore = defineStore(
  'user',
  () => {
    // state
    const userModel = ref<Partial<DataInfo<number>>>({}) // 用户信息

    // getters
    const getUser = computed(() => userModel.value)

    // actions
    // 登录操作
    const doLogin = async (params: Partial<LoginReq>) => {
      const { loginName, password, verifyCode } = params
      const loginParams: LoginReq = {
        loginName: loginName ?? '',
        password: password ?? '',
      }
      if (verifyCode) loginParams.verifyCode = verifyCode
      // 调用登录接口
      const { model } = await userApi.login(loginParams)
      setToken(model.token)
    }

    // 退出登录
    const doLogout = () => {
      removeToken()
      useMultiTagsStore().handleTags('equal', [...routerArrays])
      resetRouter()
      router.push('/login')
    }

    return {
      // state
      userModel,
      // getters
      getUser,
      // actions
      doLogin,
      doLogout,
    }
  },
  { persist: true },
)
